﻿using Css_VoteSys.Models.Database;
using Css_VoteSys.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Css_VoteSys.Controllers
{
    /// <summary>
    /// 获奖类型
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AwardCategoryController : ControllerBase
    {
        private readonly Css_VoteSysContext _db;
        private readonly IUserService _UserService;

        /// <summary>
        /// 奖项分类控制器
        /// </summary>
        /// <param name="db"></param>
        public AwardCategoryController(Css_VoteSysContext db, IUserService UserService)
        {
            _db = db;
            _UserService = UserService;
        }

        /// <summary>
        /// 创建奖项分类(需登录、管理员)
        /// </summary>
        /// <param name="AwardCategoryName">奖项分类名称</param>
        /// <returns></returns>
        [HttpPost]
        public string CreateAwardCategory(string AwardCategoryName)
        {
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
            if (UserId == null) { return "请先登录"; }
            var result = _UserService.IsRoot(Convert.ToInt32(UserId));
            if (result)
            {
                if (_db.AwardCategories.Any(x => x.AwardCategoryName == AwardCategoryName)) return "奖项分类已存在";
                _db.AwardCategories.Add(new AwardCategory
                {
                    AwardCategoryName = AwardCategoryName,
                });
                //保存更改
                var row = _db.SaveChanges();
                if (row > 0)
                    return "创建奖项分类成功";
                return "创建奖项分类失败";
            }
            return "您没有权限";
        }

        /// <summary>
        /// 查询所有奖项分类
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<AwardCategory> SelectAwardCategory()
        {
            return _db.AwardCategories.ToList();
        }
    }
}
